<template>
  <div class="home_div">
    <van-popup
      v-model="show"
      round
      position="bottom"
      :style="{ height: '65%' }"
    >
      <div class="btn-group">
        <div @click="cancelPopup">取消</div>
        <div @click="submit">确定</div>
      </div>
      <div id="search">
        <van-field
          left-icon="search"
          v-model="searchValue"
          center
          clearable
          label=""
          placeholder="请输入要搜索的位置"
        >
        <template #button>
    <van-button size="small" type="info" @click="seachAddress">搜索</van-button>
  </template>
        </van-field>
        <!-- <van-button size="small" type="primary">查询</van-button> -->
      </div>
      <div v-if="address" style="color:#999;font-size:0.24rem;padding:0 0.2rem 0.2rem 0.2rem">已选中:{{address}}</div>
      <div id="container" style="height: 40vh; width: 100%"></div>
    </van-popup>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
    props:['lons','lats','region','code'],
  data() {
    return {
      show: true,
      searchValue: "",
      lng: this.lons || "116.397428", // 使用传入的经度或默认值
      lat: this.lats || "39.90923", // 使用传入的纬度或默认值
      map: null,
      aMap: null,
      placeSearch: null,
      geoCoder: null,
      marker: null,
      adcode: this.code ||"",
      address: this.region ||"",
    };
  },
  mounted() {
    this.initMap([this.lng, this.lat]);
  },
  methods: {
    initMap(arr) {
      window._AMapSecurityConfig = {
        securityJsCode: "638b1bb3fefe982cdf2a8db2cf2a7846",
      };

      AMapLoader.load({
        key: "ac8b3896464d5d2b7735e62100bee1d0",
        version: "2.0",
        plugins: [
          "AMap.ToolBar",
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.Geocoder",
          "AMap.Marker",
        ],
      })
        .then((AMap) => {
          this.aMap = AMap;
          this.map = new AMap.Map("container", {
            viewMode: "3D",
            zoom: 10,
            center: arr,
            resizeEnable: true,
          });

          const toolBar = new AMap.ToolBar({
            position: {
              top: "20px",
              right: "51px",
            },
          });

          this.geoCoder = new AMap.Geocoder({
            city: "全国",
            radius: 1000,
          });

          this.placeSearch = new AMap.PlaceSearch({
            map: this.map,
          });

          this.map.on("click", this.clickMap);
          this.map.addControl(toolBar);
        })
        .catch((e) => {
          console.error(e);
        });
    },
    clickMap(e) {
      if (!e || !e.lnglat) {
        return;
      }
      this.lng = e.lnglat.lng;
      this.lat = e.lnglat.lat;
      this.removeMarker();
      this.setMapMarker();
      this.map.setCenter([this.lng, this.lat]); // 设置地图中心为点击位置
      this.map.setZoom(15); // 设置缩放级别
      this.regeocoder();
    },
    seachAddress() {
      if (this.searchValue !== "") {
        this.map.clearMap(); // 清除地图上的所有覆盖物
        this.removeMarker(); // 移除之前的标记（如果有）

        this.map.plugin(["AMap.PlaceSearch"], () => {
          const placeSearch = new AMap.PlaceSearch({
            city: "110010",
            map: this.map,
          });
          placeSearch.search(this.searchValue, (status, result) => {
            if (status === "complete" && result.poiList.pois.length) {
              const firstPoi = result.poiList.pois[0]; // 获取第一条符合的 POI
              this.lng = firstPoi.location.lng; // 获取经度
              this.lat = firstPoi.location.lat; // 获取纬度

              // 放大到该地点
              this.map.setCenter([this.lng, this.lat]); // 设置地图中心
              this.map.setZoom(15); // 设置缩放级别

              // this.setMapMarker(); // 如果不需要标记，可以注释掉
              this.regeocoder(); // 调用逆地理编码获取地址信息
            } else {
              this.$toast("未找到相关地点");
            }
          });
        });
      } else {
        this.$toast("请输入地址");
      }
    },
    setMapMarker() {
      if (this.lng && this.lat) {
        this.marker = new AMap.Marker({
          position: [this.lng, this.lat],
        });
        this.marker.setMap(this.map); // 将标记添加到地图
        this.map.setFitView(); // 调整视图以适应标记
      }
    },
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    regeocoder() {
      const lnglat = [this.lng, this.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          // console.log(result);
          this.address = result.regeocode.formattedAddress;
          this.adcode = result.regeocode.addressComponent.adcode;
          console.log("地址:", result.regeocode.formattedAddress);
        }
      });
    },
    cancelPopup(){
        let params={
            longitude:"",
            latitude:"",
            region_code:"",
            region_name:""
        }
        this.show=false
        // console.log(params);
        
        this.$emit("marker",params,1)
    },
    submit(){
        let params={
            longitude:this.lng,
            latitude:this.lat,
            region_code:this.adcode,
            region_name:this.address
        }
        this.show=false
        // console.log(params);
        
        this.$emit("marker",params,0)
    }
  },
};
</script>

<style scoped>
.home_div {
  /* padding: 20px; */
}
.btn-group {
  padding: 0.3rem;
  display: flex;
  justify-content: space-between;
  font-size: 0.28rem;
  color: #333;
  border-bottom: 1px solid #F2F4F5;
  div:last-child {
    color: #F32A23;
  }
}
#search{
    width:98%;
    margin:10px auto;
    display:flex;
    .van-field__body{
        /* border:1px solid #ccc; */
        padding-left:0.6rem;
        border-radius:30px;
        background: #F4F4F4;
    }
    .van-field__left-icon{
      z-index: 999;
      position: absolute;
      left: 25px;
    }
    .van-button{
        width:100%;
        margin-right:0.2rem;
        margin-bottom:.02rem;
        border-radius: 40px;
        background: linear-gradient( 135deg, #FF5851 0%, #E9011B 100%);
        border: none;
    }
}
#container {
  width: 95% !important;
  height: 40vh;
  margin: 0 auto;
  /* height: 50vh; */
}
</style>
